#include "Level5.h"
#include "GameplayBackground.h"

#define SCRWIDTH 480

#define MAX_SHIP_RESPAWN_TIME 23.0f
#define NUM_LEVEL_SHIPS 20

#define ROATION_SPEED 1.0f

Level5::~Level5()
{ }

void Level5::Load( Dock* docks, GameplayBackground* background )
{
	m_roation_status = 0;
	background->Load( "level5_shore_bg_top", "level5_shore_bg_bottom" );   
	
	// setup the docks
	docks[0].Load( CIwFVec2(238, 175), CIwFVec2(-1,0), DockType::RED );
	docks[1].Load( CIwFVec2(86, 285), CIwFVec2(-1,0), DockType::YELLOW );
	
	m_time_for_next_ship = 0;
	m_num_added_ships = 0;
	m_num_active_ships = 0;
}

void Level5::Unload()
{ }

LevelUpdateReturnStatus::Enum Level5::Update( DockType::Enum *_type, CIwFVec2* p1, CIwFVec2* p2, float dt )
{
	m_roation_status += ROATION_SPEED * dt;
	// check if we should lounch a new ship
	if( m_time_for_next_ship <= 0.0f && m_num_added_ships < NUM_LEVEL_SHIPS ) {
	
		m_time_for_next_ship = ((rand() % 1000) / 1000.0f) * MAX_SHIP_RESPAWN_TIME;
		// start a new ship, start at a random pos
		// firstly decide on which side of the screen to start
		
		int y1 = 0;
		int y2 = 0;
		
		int x1 = 0;
		int x2 = 0;
		
		int type = rand() % 100;
		
		if( type >= 50 ) {
			type = 0;
		} else {
			type = 1;
		}
		
		if( (rand() % 100) > 50 ) {
			// get two y position to calculate the direction we will be moving in
			y1 = (rand() % (230 - 60) ) + 60;
			y2 = (rand() % (230 - 60) ) + 60;
			
			x1 = -40;
			x2 = 00;
			
		} else {
			
			y1 = (rand() % (134 - 105) ) + 105;
			y2 = (rand() % (134 - 105) ) + 105;
			
			x1 = (SCRWIDTH + 40);
			x2 = (SCRWIDTH);
		}
		
		// store the data for the new ship
		*_type = (DockType::Enum) type;
		p1->x = (float) x1;
		p1->y = (float) y1;
		
		p2->x = (float) x2;
		p2->y = (float) y2;
		
		return LevelUpdateReturnStatus::START_SHIP;
	}
	
	
	if( m_num_added_ships >= NUM_LEVEL_SHIPS && m_num_active_ships == 0 )  {
		return LevelUpdateReturnStatus::LEVEL_COMPLETE;
	}
	
	m_time_for_next_ship -= dt;

	return LevelUpdateReturnStatus::DO_NOTHING; 
}

void Level5::Draw ()
{ }

void Level5::ShipAdded( Ship *ship )
{
	++ m_num_added_ships;
	++ m_num_active_ships;
}

void Level5::ShipOutOfScreen( Ship *ship )
{
	-- m_num_active_ships;
}